﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

using Centrica.TaskManager.Data;

using Microsoft.Practices.Composite.Presentation.Commands;

namespace Centrica.TaskManager.Task
{
    public class TaskViewModel : INotifyPropertyChanged
    {

        private Data.Task _task;

        public TaskViewModel()
        {

            Initialize();

            _task = new Data.Task();

        }

        public TaskViewModel(Data.Task task)
        {

            Initialize();

            _task = task;

        }


        private void Initialize()
        {
        
            this.SaveTaskCommand = new DelegateCommand<Data.Task>(OnSaveTask);
        
        }

        public ICommand SaveTaskCommand { get; set; }

        public Data.Task Task
        {
            get { return _task; }
            set 
            {

                if (_task != value)
                {

                    _task = value;

                    OnPropertyChanged("Task");
                
                }
            
            }
        }

        public ObjectQuery<TaskStatus> TaskStatus
        {
            get {return  Data.ContextManager.Context.TaskStatus;}
        }

        public ObjectQuery<TaskType> TaskType
        {
            get {return  Data.ContextManager.Context.TaskType;}
        }

        protected virtual void OnSaveTask(Data.Task task)
        {

            EntityObject obj = (EntityObject)task;
            
            task.UserName = "";
            task.TmsChange = DateTime.Now;

            if(obj.EntityState == System.Data.EntityState.Detached)
            {
                Data.ContextManager.Context.AddObject("Task", task);
            }

            Data.ContextManager.Context.SaveChanges();
            Data.ContextManager.Context.Refresh(System.Data.Objects.RefreshMode.StoreWins, Data.ContextManager.Context.Task);
         
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));                        
            }
        }

        #endregion
    }
}
